<template>
  <div class="course-list-app">
    <!-- 调试信息 -->
    <div v-if="false" style="background: #ffeb3b; padding: 10px; margin: 10px; border-radius: 5px; color: #333;">
      <h4>调试信息</h4>
      <p>currentUser: {{ currentUser }}</p>
      <p>currentUser类型: {{ typeof currentUser }}</p>
      <p v-if="currentUser">用户名: {{ currentUser.name }}</p>
      <p>localStorage.currentUser: {{ localStorage.getItem('currentUser') }}</p>
    </div>
    
    <!-- Header -->
    <AppHeader 
      :current-user="currentUser"
      :courses="courses"
      :video-courses="videoCourses"
      :tasks="tasks"
      :show-search="true"
      @login="showLoginModal"
      @register="showRegisterModal"
      @logout="handleLogout"
      @show-battle-power="showBattlePowerModal"
    />

    <!-- Navigation Breadcrumb -->
    <nav class="breadcrumb-nav">
      <div class="breadcrumb-content">
        <div class="breadcrumb">
          <span class="breadcrumb-item">
            <i class="fas fa-home"></i>
            笔记中心
          </span>
        </div>
      </div>
    </nav>
    
    <!-- 调试按钮 -->
    <div v-if="false" style="padding: 10px; text-align: center;">
      <button @click="forceRefresh" style="padding: 5px 10px; background: #4CAF50; color: white; border: none; border-radius: 3px; cursor: pointer;">
        强制刷新用户状态
      </button>
    </div>

    <!-- Main Content -->
    <main class="main-content with-sidebar">
      <!-- Left Sidebar Container -->
      <AppSidebar 
        :tasks="tasks"
        :current-user="currentUser"
        :courses="courses"
        :video-courses="videoCourses"
        :total-course-chapters="totalCourseChapters"
        :total-video-chapters="totalVideoChapters"
        :recent-activity="recentActivity"
        @filter-tasks="handleTaskFilter"
        @toggle-task="handleToggleTask"
      />
      
      <!-- Main Content Area -->
      <div class="content-area">
        <!-- Welcome Banner -->
        <section class="welcome-banner">
          <div class="banner-content">
            <div class="banner-text">
              <h2>欢迎来到讲懂笔记</h2>
              <p>浏览您的笔记、视频课程，预览章节内容，开始您的学习之旅</p>
            </div>
            <div class="banner-stats">
              <div class="stat-item">
                <div class="stat-number">{{ courses.length }}</div>
                <div class="stat-label">笔记总数</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ videoCourses.length }}</div>
                <div class="stat-label">视频课程</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ totalCourseChapters }}</div>
                <div class="stat-label">笔记章节</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ totalVideoChapters }}</div>
                <div class="stat-label">视频章节</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ recentActivity }}</div>
                <div class="stat-label">最近更新</div>
              </div>
            </div>
          </div>
        </section>

        <!-- Course Grid -->
        <CourseSection 
          :courses="courses"
          :current-user="currentUser"
          :view-mode="courseViewMode"
          :show-actions="false"
          @view-change="handleCourseViewChange"
          @show-login="showLoginModal"
          @show-register="showRegisterModal"
        />
        
        <!-- Video Courses Section -->
        <VideoSection 
          :video-courses="videoCourses"
          :current-user="currentUser"
          :view-mode="videoViewMode"
          :show-actions="false"
          @view-change="handleVideoViewChange"
          @show-login="showLoginModal"
          @show-register="showRegisterModal"
        />
      </div>
    </main>
    
    <!-- Login Modal -->
    <LoginModal 
      v-if="showLogin"
      @close="hideLoginModal"
      @login-success="handleLoginSuccess"
      @switch-to-register="showRegisterModal"
    />
    
    <!-- Register Modal -->
    <RegisterModal 
      v-if="showRegister"
      @close="hideRegisterModal"
      @register-success="handleRegisterSuccess"
      @switch-to-login="showLoginModal"
    />
    
    <!-- Battle Power Information Modal -->
    <BattlePowerModal 
      v-if="showBattlePower"
      @close="hideBattlePowerModal"
    />
  </div>
</template>

<script>
import AppHeader from '@/components/AppHeader.vue'
import AppSidebar from '@/components/AppSidebar.vue'
import CourseSection from '@/components/CourseSection.vue'
import VideoSection from '@/components/VideoSection.vue'
import LoginModal from '@/components/LoginModal.vue'
import RegisterModal from '@/components/RegisterModal.vue'
import BattlePowerModal from '@/components/BattlePowerModal.vue'
import apiService from '@/services/api.js'

export default {
  name: 'HomePage',
  components: {
    AppHeader,
    AppSidebar,
    CourseSection,
    VideoSection,
    LoginModal,
    RegisterModal,
    BattlePowerModal
  },
  data() {
    return {
      courses: [],
      videoCourses: [],
      tasks: [],
      currentUser: null,
      courseViewMode: 'grid',
      videoViewMode: 'grid',
      currentTaskFilter: 'all',
      showLogin: false,
      showRegister: false,
      showBattlePower: false,
      battlePowerRefreshInterval: null // 用于存储战斗力刷新定时器
    }
  },
  computed: {
    totalCourseChapters() {
      return this.courses.reduce((total, course) => {
        return total + (course.chapters ? course.chapters.length : 0)
      }, 0)
    },
    totalVideoChapters() {
      return this.videoCourses.reduce((total, course) => {
        return total + (course.chapters ? course.chapters.length : 0)
      }, 0)
    },
    recentActivity() {
      // Calculate recent activity based on last 7 days
      const sevenDaysAgo = new Date()
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
      
      let count = 0
      this.courses.forEach(course => {
        if (new Date(course.lastModified || course.createdAt) > sevenDaysAgo) {
          count++
        }
      })
      this.videoCourses.forEach(course => {
        if (new Date(course.lastModified || course.createdAt) > sevenDaysAgo) {
          count++
        }
      })
      return count
    }
  },
  async mounted() {
    await this.checkAuthStatus()
    this.loadData()
    
    // 设置定时器，每5分钟刷新一次战斗力
    this.battlePowerRefreshInterval = setInterval(() => {
      if (this.currentUser && this.currentUser.id) {
        this.refreshBattlePower()
      }
    }, 5 * 60 * 1000) // 5分钟
  },
  beforeUnmount() {
    // 清除定时器
    if (this.battlePowerRefreshInterval) {
      clearInterval(this.battlePowerRefreshInterval)
    }
  },
  methods: {
    async loadData() {
      // 修改为无论用户是否登录都加载所有用户的笔记和视频
      try {
        // 获取所有用户的笔记和视频课程（不传递用户ID参数）
        const [coursesRes, videoCoursesRes] = await Promise.all([
          apiService.getCourses(),
          apiService.getVideoCourses()
        ])
        
        this.courses = coursesRes.courses || []
        this.videoCourses = videoCoursesRes.courses || []
        
        // 如果用户已登录，仍然加载用户的任务数据
        if (this.currentUser) {
          try {
            const tasksRes = await apiService.getTasks()
            this.tasks = tasksRes.tasks || []
          } catch (error) {
            console.error('加载任务数据失败:', error)
            this.tasks = []
          }
        } else {
          this.tasks = []
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        // 如果加载失败，使用空数据
        this.courses = []
        this.videoCourses = []
        this.tasks = []
      }
    },
    async checkAuthStatus() {
      const savedUser = localStorage.getItem('currentUser')
      const savedToken = localStorage.getItem('auth_token')
      
      if (savedUser && savedToken) {
        this.currentUser = JSON.parse(savedUser)
        // 验证token有效性
        await this.validateToken()
      }
    },
    async validateToken() {
      try {
        const user = await apiService.getCurrentUser()
        // 确保正确处理返回的用户数据
        const userData = user.data || user
        this.currentUser = userData
        localStorage.setItem('currentUser', JSON.stringify(userData))
      } catch (error) {
        console.error('Token验证失败:', error)
        // Token无效，清除登录状态
        this.currentUser = null
        apiService.clearAuth()
      }
    },
    showLoginModal() {
      this.showLogin = true
    },
    hideLoginModal() {
      this.showLogin = false
    },
    showRegisterModal() {
      this.showRegister = true
    },
    hideRegisterModal() {
      this.showRegister = false
    },
    showBattlePowerModal() {
      this.showBattlePower = true
    },
    hideBattlePowerModal() {
      this.showBattlePower = false
    },
    handleLoginSuccess(user) {
      this.currentUser = user
      // 强制触发Vue的响应式更新
      this.$forceUpdate()
      this.hideLoginModal()
      // Token已经在apiService.login中处理
      // 重新加载用户数据
      this.loadData()
    },
    handleRegisterSuccess(user) {
      this.currentUser = user
      this.hideRegisterModal()
      // Token已经在apiService.register中处理
    },
    async handleLogout() {
      try {
        await apiService.logout()
      } catch (error) {
        console.error('注销失败:', error)
      } finally {
        this.currentUser = null
      }
    },
    handleCourseViewChange(view) {
      this.courseViewMode = view
    },
    handleVideoViewChange(view) {
      this.videoViewMode = view
    },
    handleTaskFilter(filter) {
      this.currentTaskFilter = filter
    },
    async handleToggleTask(taskId) {
      try {
        // 立即更新本地任务状态以提供即时反馈
        const taskIndex = this.tasks.findIndex(task => task.id === taskId);
        if (taskIndex !== -1) {
          // 创建任务副本
          const updatedTasks = [...this.tasks];
          const task = { ...updatedTasks[taskIndex] };
          
          // 切换状态
          if (task.status === 'completed') {
            task.status = 'pending';
            task.progress = 0;
          } else {
            task.status = 'completed';
            task.progress = 100;
          }
          
          // 更新任务数组
          updatedTasks[taskIndex] = task;
          this.tasks = updatedTasks;
        }
        
        // 调用API更新任务状态
        await apiService.toggleTaskStatus(taskId);
      } catch (error) {
        console.error('切换任务状态失败:', error);
        // 如果API调用失败，恢复之前的状态
        this.loadData();
      }
    },
    
    // 调试方法：强制刷新用户状态
    forceRefresh() {
      console.log('强制刷新用户状态');
      const savedUser = localStorage.getItem('currentUser');
      console.log('localStorage中的用户信息:', savedUser);
      if (savedUser) {
        try {
          this.currentUser = JSON.parse(savedUser);
          console.log('设置currentUser为:', this.currentUser);
        } catch (e) {
          console.error('解析用户信息失败:', e);
        }
      } else {
        this.currentUser = null;
      }
    },
    // 修改方法：刷新战斗力
    async refreshBattlePower() {
      if (!this.currentUser || !this.currentUser.id) return
      
      try {
        await apiService.refreshBattlePower()
        // 刷新用户信息以获取最新的战斗力
        await this.checkAuthStatus()
      } catch (error) {
        console.error('刷新战斗力失败:', error)
      }
    }
  }
}
</script>

<style>
/* Import the CSS from the original styles.css */
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css');

/* Base Styles - moved from original styles.css */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  font-size: 12px;
  line-height: 1.6;
  color: #2c3e50;
  background-color: #f8fafc;
}

/* Course List App Styles */
.course-list-app {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* Welcome Banner */
.welcome-banner {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  padding: 3rem 2rem;
  margin-bottom: 2rem;
}

.banner-content {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 2rem;
}

.banner-text h2 {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 0.5rem;
  color: #1e293b;
}

.banner-text p {
  font-size: 12px;
  color: #64748b;
}

.banner-stats {
  display: flex;
  gap: 2rem;
}

.stat-item {
  text-align: center;
  min-width: 80px;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 0.25rem;
  color: #1e293b;
}

.stat-label {
  font-size: 11px;
  color: #64748b;
}

/* Breadcrumb Navigation */
.breadcrumb-nav {
  background: white;
  border-bottom: 1px solid #e2e8f0;
  padding: 0.75rem 0;
  margin-bottom: 5px;
}

.breadcrumb-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 2rem;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 12px;
  color: #64748b;
}

.breadcrumb-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  position: relative;
}

/* Main Content */
.main-content {
  flex: 1;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
  padding: 0 2rem;
}

.main-content.with-sidebar {
  display: flex;
  gap: 2rem;
  align-items: flex-start;
}

.content-area {
  flex: 1;
}

@media (max-width: 768px) {
  .banner-content {
    flex-direction: column;
    text-align: center;
  }
  
  .banner-stats {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .main-content.with-sidebar {
    flex-direction: column;
  }
  
  .main-content {
    padding: 0 1rem;
  }
}
</style>